﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Xml;

namespace DeloUtils.Migra
{
    class ImportDocuments
    {
        public static event ProgressHandler CurrentRows;
        public static LocalDBCompact localdb;
        public static Int32 CountFiles=0;
        public static System.Windows.Forms.TextBox txtImportError;
        public static bool checksave = true;
        private static string _Folder;
        public static void Import12mss(String Folder, OleDbConnection connection, EApi.Head ApiConnection)
        {
            _Folder = Folder;
            List<string> files = new List<string>(System.IO.Directory.EnumerateFiles(Folder, "*.xml"));            
            XmlDocument doc = new XmlDocument();
            CountFiles = files.Count;
            for (int progress = 0; progress < files.Count; progress++)
            {
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    doc.Load(files[progress]);
                    //Int32 year =  Int32.Parse(localdb.convertDate(doc.SelectSingleNode("//rc/DOC_DATE").InnerText).Substring(0,4));
                    SaveRC(doc, ApiConnection);
                    CurrentRows(progress);
                }
                catch (Exception ex)
                {
                    System.IO.File.AppendAllText(Folder + "\\Import.log", files[progress] + " \n\r" + ex.Message + " \n\r");
                    txtImportError.Text += " \n\r" + files[progress] + " \n\r" + ex.Message + " \n\r";
                    txtImportError.Update();
                }
            }
            localdb.Connection.Close();
        }

        public static Int32 SaveRC(XmlDocument doc, EApi.Head ApiConnection)
        {
                string _rc_isn = doc.SelectSingleNode("//rc/@isn").InnerText;
                if (checksave && (localdb.isIsnRc(Int32.Parse(_rc_isn)))) return 0;
                dynamic proc = ApiConnection.GetProc("add_rc");
                proc.Parameters.Append(proc.CreateParameter("aIsn", 3, 3, 4, (float)0));
                proc.Parameters.Append(proc.CreateParameter("aDueCard", 200, 1, 48, localdb.syncCard("0.")));
                proc.Parameters.Append(proc.CreateParameter("aIsnCab", 3, 1, 4, (float)localdb.syncCabinet(0)));
                if (doc.SelectNodes("//rc/DOCGROUP").Count > 0) proc.Parameters.Append(proc.CreateParameter("aDueDocgroup", 200, 1, 48, localdb.syncDocgroup(doc.SelectSingleNode("//rc/DOCGROUP"))));
                else proc.Parameters.Append(proc.CreateParameter("aDueDocgroup", 200, 1, 48, "0."));
                if (doc.SelectNodes("//rc/ORDER_NUM").Count > 0) proc.Parameters.Append(proc.CreateParameter("aOrderNum", 3, 1, 4, (float)Int32.Parse(doc.SelectSingleNode("//rc/ORDER_NUM").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aOrderNum", 3, 1, 4, 0));
                if (doc.SelectNodes("//rc/FREE_NUM").Count > 0) proc.Parameters.Append(proc.CreateParameter("aFreeNum", 200, 1, 64, doc.SelectSingleNode("//rc/FREE_NUM").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aFreeNum", 200, 1, 64, ""));
                if (doc.SelectNodes("//rc/DOC_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aDocDate", 200, 1, 20, localdb.convertDate(doc.SelectSingleNode("//rc/DOC_DATE").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aDocDate", 200, 1, 20, DBNull.Value));
                if (doc.SelectNodes("//rc/SECURLEVEL").Count > 0) proc.Parameters.Append(proc.CreateParameter("aSecurlevel", 3, 1, 4, (float)localdb.syncSecurlevel(doc.SelectSingleNode("//rc/SECURLEVEL"))));
                else proc.Parameters.Append(proc.CreateParameter("aSecurlevel", 3, 1, 4, (float)1));
                if (doc.SelectNodes("//rc/CONSISTS").Count > 0) proc.Parameters.Append(proc.CreateParameter("aConsists", 200, 1, 255, doc.SelectSingleNode("//rc/CONSISTS").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aConsists", 200, 1, 255, ""));
                if (doc.SelectNodes("//rc/SPECIMEN").Count > 0) proc.Parameters.Append(proc.CreateParameter("aSpecimen", 200, 1, 64, doc.SelectSingleNode("//rc/SPECIMEN").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aSpecimen", 200, 1, 64, ""));
                if (doc.SelectNodes("//rc/PLAN_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aPlanDate", 200, 1, 20, localdb.convertDate(doc.SelectSingleNode("//rc/PLAN_DATE").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aPlanDate", 200, 1, 20, DBNull.Value));
                if (doc.SelectNodes("//rc/FACT_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aFactDate", 200, 1, 20, localdb.convertDate(doc.SelectSingleNode("//rc/FACT_DATE").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aFactDate", 200, 1, 20, DBNull.Value));
                if (doc.SelectNodes("//rc/CONTROL_STATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aControlState", 3, 1, 4, (float)localdb.syncControlState(doc.SelectSingleNode("//rc/CONTROL_STATE").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aControlState", 3, 1, 4, DBNull.Value));
                if (doc.SelectNodes("//rc/ANNOTAT").Count > 0) proc.Parameters.Append(proc.CreateParameter("aAnnotat", 200, 1, 2000, doc.SelectSingleNode("//rc/ANNOTAT").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aAnnotat", 200, 1, 2000, ""));
                if (doc.SelectNodes("//rc/NOTE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aNote", 200, 1, 2000, doc.SelectSingleNode("//rc/NOTE").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aNote", 200, 1, 2000, ""));
                if (doc.SelectNodes("//rc/WHOS").Count > 0) proc.Parameters.Append(proc.CreateParameter("aDuePersonWhos", 200, 1, 8000, localdb.syncWho(doc.SelectSingleNode("//rc/WHOS"))));
                else proc.Parameters.Append(proc.CreateParameter("aDuePersonWhos", 200, 1, 8000, DBNull.Value));
                if (doc.SelectNodes("//rc/DELIVERY").Count > 0) proc.Parameters.Append(proc.CreateParameter("aIsnDelivery", 3, 1, 4, (float)localdb.syncDelivery(doc.SelectSingleNode("//rc/DELIVERY"))));
                else proc.Parameters.Append(proc.CreateParameter("aIsnDelivery", 3, 1, 4, DBNull.Value));
                if (doc.SelectNodes("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/DUE_ORGANIZ").Count > 0) proc.Parameters.Append(proc.CreateParameter("aDueOrganiz", 200, 1, 48, localdb.syncOrganiz(doc.SelectSingleNode("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/DUE_ORGANIZ"))));
                else proc.Parameters.Append(proc.CreateParameter("aDueOrganiz", 200, 1, 48, ""));
                proc.Parameters.Append(proc.CreateParameter("aIsnContact", 3, 1, 4, DBNull.Value));
                if (doc.SelectNodes("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/CORRESP_NUM").Count > 0) proc.Parameters.Append(proc.CreateParameter("aCorrespNum", 200, 1, 64, doc.SelectSingleNode("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/CORRESP_NUM").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aCorrespNum", 200, 1, 64, ""));
                if (doc.SelectNodes("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/CORRESP_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aCorrespDate", 200, 1, 20, localdb.convertDate(doc.SelectSingleNode("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/CORRESP_DATE").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aCorrespDate", 200, 1, 20, DBNull.Value));
                if (doc.SelectNodes("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/CORRESP_SIGN").Count > 0) proc.Parameters.Append(proc.CreateParameter("aCorrespSign", 200, 1, 255, doc.SelectSingleNode("//rc/CORRESPS/CORRESP[CORRESP_KIND='1']/CORRESP_SIGN").InnerText));
                else proc.Parameters.Append(proc.CreateParameter("aCorrespSign", 200, 1, 255, ""));
                if (doc.SelectNodes("//rc/REF_LETTERS/REF_LETTER").Count > 0)
                    proc.Parameters.Append(proc.CreateParameter("aIsnCitizen", 3, 1, 4, (float)localdb.syncCitizen(doc.SelectSingleNode("//rc/REF_LETTERS/REF_LETTER"))));
                else proc.Parameters.Append(proc.CreateParameter("aIsnCitizen", 3, 1, 4, DBNull.Value));
                if (doc.SelectNodes("//rc/ISCOLLECTIVE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aIsCollective", 3, 1, 4, localdb.convertInt(doc.SelectSingleNode("//rc/ISCOLLECTIVE").InnerText)));
                else proc.Parameters.Append(proc.CreateParameter("aIsCollective", 3, 1, 4, (float)0));
                proc.Parameters.Append(proc.CreateParameter("aIsAnonim", 3, 1, 4, (float)0));
                if (doc.SelectNodes("//rc/SIGNS").Count > 0) proc.Parameters.Append(proc.CreateParameter("aSigns", 200, 1, 8000, localdb.syncSign(doc.SelectSingleNode("//rc/SIGNS"))));
                else proc.Parameters.Append(proc.CreateParameter("aSigns", 200, 1, 8000, ""));
                if (doc.SelectNodes("//rc/PERSON_EXE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aDuePersonExe", 200, 1, 8000, localdb.syncDepartment(doc.SelectSingleNode("//rc/PERSON_EXE"))));
                else proc.Parameters.Append(proc.CreateParameter("aDuePersonExe", 200, 1, 8000, ""));
                proc.Parameters.Append(proc.CreateParameter("aIsnNomenc", 3, 1, 4, DBNull.Value));
                proc.Parameters.Append(proc.CreateParameter("aNothardcopy", 3, 1, 4, DBNull.Value));
                proc.Parameters.Append(proc.CreateParameter("aCito", 3, 1, 4, (float)0));
                proc.Parameters.Append(proc.CreateParameter("aIsnLinkingDoc", 3, 1, 4, DBNull.Value));
                proc.Parameters.Append(proc.CreateParameter("aIsnLinkingPrj", 3, 1, 4, DBNull.Value));
                proc.Parameters.Append(proc.CreateParameter("aIsnClLink", 3, 1, 4, (float)0));
                proc.Parameters.Append(proc.CreateParameter("aCopyShablon", 200, 1, 20, ""));
                if (doc.SelectNodes("//rc/VISAS").Count > 0) proc.Parameters.Append(proc.CreateParameter("aVisas", 200, 1, 8000, localdb.syncSign(doc.SelectSingleNode("//rc/VISAS"))));
                else proc.Parameters.Append(proc.CreateParameter("aVisas", 200, 1, 8000, ""));
                proc.Parameters.Append(proc.CreateParameter("aEDocument", 3, 1, 2, DBNull.Value));
                ApiConnection.ExecuteProc(proc);
                if (ApiConnection.ErrCode != 0) throw new Exception("SaveRC [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
                object result = proc.Parameters("aIsn").Value;

                if (result != null)
                {
                    localdb.setNewIsn("RC", Int32.Parse(_rc_isn), (Int32)result);
                    XmlNodeList _resolution = doc.SelectNodes("//rc/RESOLUTIONS/RESOLUTION");
                    for (int i = 0; i < _resolution.Count; i++)
                    {
                        SaveResolution(_resolution[i], ApiConnection, (Int32)result);
                    }

                    SaveRubric(doc.SelectSingleNode("//rc/REF_RUBRICS"), ApiConnection, (Int32)result);
                    SaveSend(doc.SelectSingleNode("//rc/SENDS"), ApiConnection, (Int32)result);
                    SaveCoverDoc(doc.SelectSingleNode("//rc/CORRESPS"), ApiConnection, (Int32)result);
                    SaveJournal(doc.SelectSingleNode("//rc/JOURNAL"), ApiConnection, (Int32)result);
                    SaveLinks(doc.SelectSingleNode("//rc/LINKS"), ApiConnection, (Int32)result, _rc_isn);
                    SaveArRcValues(doc.SelectSingleNode("//rc/AR_RC_VALUE"), ApiConnection, (Int32)result);

                    return (Int32)result;
                }
                return 0;
        }

        private static Int32 SaveResolution(XmlNode resolution, EApi.Head ApiConnection, Int32 isn_doc)
        {
            if (resolution == null || ApiConnection == null || isn_doc == 0) return 0;
            dynamic proc = ApiConnection.GetProc("add_resolution");
            //proc.Parameters.Append(proc.CreateParameter("an_isn_resolution", 3, 3, 4, DBNull.Value));
            if (resolution.SelectNodes("KIND_RESOLUTION").Count > 0) proc.Parameters.Append(proc.CreateParameter("an_kind_resolution", 3, 1, 4, (float)Int32.Parse(resolution.SelectSingleNode("KIND_RESOLUTION").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("an_kind_resolution", 3, 1, 4, (float)1));
            proc.Parameters.Append(proc.CreateParameter("an_isn_ref_doc", 3, 1, 4, (double)isn_doc));
            proc.Parameters.Append(proc.CreateParameter("an_isn_parent_resolution", 3, 1, 4, DBNull.Value));
            if (resolution.SelectNodes("DUE").Count > 0) proc.Parameters.Append(proc.CreateParameter("an_isn_author", 200, 1, 48, localdb.syncDepartment(resolution.SelectSingleNode("DUE"))));
            else proc.Parameters.Append(proc.CreateParameter("an_isn_author", 200, 1, 48, "-1"));
            proc.Parameters.Append(proc.CreateParameter("as_item_number", 200, 1, 64, DBNull.Value));
            if (resolution.SelectNodes("RESOLUTION_TEXT").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_resolution_text", 200, 1, 2000, resolution.SelectSingleNode("RESOLUTION_TEXT").InnerText));
            else proc.Parameters.Append(proc.CreateParameter("as_resolution_text", 200, 1, 2000, ""));
            proc.Parameters.Append(proc.CreateParameter("an_isn_category", 3, 1, 4, DBNull.Value));
            proc.Parameters.Append(proc.CreateParameter("an_conf", 3, 1, 2, (float)0));
            if (resolution.SelectNodes("RESOLUTION_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("ad_resolution_date", 200, 1, 20, localdb.convertDate(resolution.SelectSingleNode("RESOLUTION_DATE").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("ad_resolution_date", 200, 1, 20, ""));
            if (resolution.SelectNodes("SEND_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("ad_send_date", 200, 1, 20, localdb.convertDate(resolution.SelectSingleNode("SEND_DATE").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("ad_send_date", 200, 1, 20, ""));
            proc.Parameters.Append(proc.CreateParameter("an_notify_author", 3, 1, 2, (float)0));
            if (resolution.SelectNodes("PLAN_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("ad_plan_date", 200, 1, 20, localdb.convertDate(resolution.SelectSingleNode("PLAN_DATE").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("ad_plan_date", 200, 1, 20, ""));
            if (resolution.SelectNodes("INTERIM_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("ad_interim_date", 200, 1, 20, localdb.convertDate(resolution.SelectSingleNode("INTERIM_DATE").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("ad_interim_date", 200, 1, 20, ""));
            if (resolution.SelectNodes("FACT_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("ad_fact_date", 200, 1, 20, localdb.convertDate(resolution.SelectSingleNode("FACT_DATE").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("ad_fact_date", 200, 1, 20, ""));
            if (resolution.SelectNodes("DUE_CONTROLLER").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_due_controller", 200, 1, 48, localdb.syncDepartment(resolution.SelectSingleNode("DUE_CONTROLLER"))));
            else if (resolution.SelectNodes("DUE").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_due_controller", 200, 1, 48, localdb.syncDepartment(resolution.SelectSingleNode("DUE"))));
            else proc.Parameters.Append(proc.CreateParameter("as_due_controller", 200, 1, 48, ""));
            if ((resolution.SelectNodes("PLAN_DATE").Count > 0) && (resolution.SelectNodes("FACT_DATE").Count > 0)) 
                proc.Parameters.Append(proc.CreateParameter("an_control_state", 3, 1, 2, 2));
            else if (resolution.SelectNodes("PLAN_DATE").Count > 0) 
                proc.Parameters.Append(proc.CreateParameter("an_control_state", 3, 1, 2, 1));
            else 
                proc.Parameters.Append(proc.CreateParameter("an_control_state", 3, 1, 2, DBNull.Value));
            if (resolution.SelectNodes("SUMMARY").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_summary", 200, 1, 2000, resolution.SelectSingleNode("SUMMARY").InnerText));
            else proc.Parameters.Append(proc.CreateParameter("as_summary", 200, 1, 2000, ""));
            proc.Parameters.Append(proc.CreateParameter("an_cascade_control", 3, 1, 2, 0));
            proc.Parameters.Append(proc.CreateParameter("an_control_duty", 3, 1, 2, 1));
            if (resolution.SelectNodes("RESUME").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_resume", 200, 1, 2000, resolution.SelectSingleNode("RESUME").InnerText));
            else proc.Parameters.Append(proc.CreateParameter("as_resume", 200, 1, 2000, ""));
            proc.Parameters.Append(proc.CreateParameter("an_left_resolution", 3, 1, 2, 1));
            proc.Parameters.Append(proc.CreateParameter("an_cycle", 3, 1, 2, 0));
            if (resolution.SelectNodes("NOTE").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_note", 200, 1, 255, resolution.SelectSingleNode("NOTE").InnerText));
            else proc.Parameters.Append(proc.CreateParameter("as_note", 200, 1, 255, ""));

            XmlNodeList replyall = resolution.SelectNodes("REPLYS/REPLY/DUE");
            string s_replyall = "";
            for (int i = 0; i < replyall.Count; i++)
            {
                try
                {
                    if (i == 0)
                    {
                        s_replyall = localdb.syncDepartmentISN(replyall[i]).ToString();
                    }
                    else
                    {
                        s_replyall = s_replyall + "|" + localdb.syncDepartmentISN(replyall[i]).ToString();
                    }
                }
                catch (Exception ex)
                {
                    //throw new Exception(string.Format("Ошибка добавления {0} -го исполнителя в резолюцию.",i) + ex.Message);
                    System.IO.File.AppendAllText(_Folder + "\\Import.log", string.Format("Ошибка добавления {0} -го исполнителя в резолюцию.", i) + " \n\r" + ex.Message + " \n\r");

                }

            }
            
            XmlNodeList replymain = resolution.SelectNodes("REPLYS/REPLY[MAIN_FLAG=1]/DUE");
            string s_replymain = "";
            for (int i = 0; i < replymain.Count; i++)
            {
                if (i == 0)
                {
                    s_replymain = localdb.syncDepartmentISN(replymain[i]).ToString();
                }
                else
                {
                    s_replymain = s_replymain + "|" + localdb.syncDepartmentISN(replymain[i]).ToString();
                }
            }
            proc.Parameters.Append(proc.CreateParameter("as_rep_isns", 200, 1, 2000, s_replyall));
            proc.Parameters.Append(proc.CreateParameter("as_rep_responsible_isns", 200, 1, 2000, s_replymain));
            proc.Parameters.Append(proc.CreateParameter("an_cab", 3, 1, 2, DBNull.Value));
            proc.Parameters.Append(proc.CreateParameter("an_is_project", 3, 1, 2, (float)0));
            ApiConnection.ExecuteProc(proc);
            if (ApiConnection.ErrCode != 0) throw new Exception("SaveResolution [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
            String sql = "SELECT MAX(ISN_RESOLUTION) FROM RESOLUTION WHERE ISN_REF_DOC=" + isn_doc.ToString();
            OleDbCommand cmd = new OleDbCommand(sql, localdb.SyncConnection);
            object res = cmd.ExecuteScalar();
            Int32 isn_resolution = Int32.Parse(res.ToString());
            //object result = proc.Parameters("an_isn_resolution").Value;
            //Int32 isn_resolution = (Int32)result;
            Data _data = new Data("RESOLUTION", DateTime.Now, Int32.Parse(resolution.SelectSingleNode("@ISN").InnerText), string.Empty,DateTime.Now,isn_resolution,string.Empty);
            _data.SaveDB(localdb);
            sql = "SELECT ISN_REPLY FROM REPLY WHERE ISN_RESOLUTION=" + isn_resolution.ToString();
            cmd = new OleDbCommand(sql, localdb.SyncConnection);
            OleDbDataReader dr = cmd.ExecuteReader();
            int j = 0;
            while (dr.Read())
            {
                res =  dr.GetValue(0);
                _data = new Data("REPLY", DateTime.Now, Int32.Parse(res.ToString()), string.Empty, DateTime.Now, isn_resolution, "RESOLUTION");
                _data.SaveDB(localdb);
                SaveReply(replyall[j], ApiConnection,Int32.Parse(res.ToString()));
                j++;
            }
            dr.Close();
            return isn_resolution;
        }

        private static void SaveReply(XmlNode reply, EApi.Head ApiConnection, Int32 isn_reply)
        {
            if (reply == null || ApiConnection == null || isn_reply == 0) return;
            dynamic proc = ApiConnection.GetProc("set_reply");
            proc.Parameters.Append(proc.CreateParameter("an_isn_reply", 3, 1, 4, (double)isn_reply));
            if (reply.SelectNodes("../REPLY_TEXT").Count > 0) proc.Parameters.Append(proc.CreateParameter("as_reply_text", 200, 1, 2000, reply.SelectSingleNode("../REPLY_TEXT").InnerText));
            else proc.Parameters.Append(proc.CreateParameter("as_reply_text", 200, 1, 2000, ""));
            if (reply.SelectNodes("../REPLY_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("ad_reply_date", 200, 1, 20, localdb.convertDate(reply.SelectSingleNode("../REPLY_DATE").InnerText)));
            else proc.Parameters.Append(proc.CreateParameter("ad_reply_date", 200, 1, 20, DBNull.Value));
            proc.Parameters.Append(proc.CreateParameter("an_status_reply", 3, 1, 4, (float)-1));
            proc.Parameters.Append(proc.CreateParameter("an_cab", 3, 1, 4, DBNull.Value));
            ApiConnection.ExecuteProc(proc);
            if (ApiConnection.ErrCode != 0) throw new Exception("[" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
        }

        private static void SaveRubric(XmlNode rubric, EApi.Head ApiConnection, Int32 isn_doc)
        {
            if (rubric == null || ApiConnection == null || isn_doc == 0) return;
            XmlNodeList rubrics = rubric.SelectNodes("REF_RUBRIC/RUBRIC");
            string _rubrics = "";
            for (int i = 0; i < rubrics.Count; i++)
            {
                dynamic proc = ApiConnection.GetProc("add_rubric");
                proc.Parameters.Append(proc.CreateParameter("aIsnDoc", 3, 1, 4, (double)isn_doc));
                _rubrics = localdb.syncRubric(rubrics[i]);
                proc.Parameters.Append(proc.CreateParameter("codes", 200, 1, 2000, _rubrics));
                proc.Parameters.Append(proc.CreateParameter("acard", 200, 1, 48, DBNull.Value));
                ApiConnection.ExecuteProc(proc);
                if (ApiConnection.ErrCode != 0) throw new Exception("SaveRubric [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
            }
        }

        private static void SaveSend(XmlNode sends, EApi.Head ApiConnection, Int32 isn_doc)
        {
            if (sends == null || ApiConnection == null || isn_doc == 0) return;
            try
            {
                XmlNodeList _sends = sends.SelectNodes("SEND/DUE_ORGANIZ");
                if (_sends == null) return;
                string organiz = "";
                string contact = "";
                string sendperson = "";
                for (int i = 0; i < _sends.Count; i++)
                {
                    organiz = localdb.syncOrganiz(_sends[i]).ToString();
                    contact = localdb.syncOrganizISN(_sends[i]).ToString();
                    if (contact.Length < 6)
                    {
                        String sql = "update ORGANIZ_CL set IMPORTDUE=null,IMPORTISN=null WHERE DUE='" +
                            _sends[i].SelectSingleNode("@DUE").InnerText + "'";
                        OleDbCommand cmd = new OleDbCommand(sql, localdb.Connection);
                        cmd.ExecuteNonQuery();
                        contact = localdb.syncOrganizISN(_sends[i]).ToString();
                    }
                    contact = (contact == "0") ? "" : contact;
                    sendperson = (_sends[i].SelectNodes("../SEND_PERSON").Count > 0) ? (_sends[i].SelectSingleNode("../SEND_PERSON").InnerText + " ") : " ";
                    if (organiz != "")
                    {
                        dynamic proc = ApiConnection.GetProc("add_send");
                        proc.Parameters.Append(proc.CreateParameter("aIsnDoc", 3, 1, 4, (double)isn_doc));
                        proc.Parameters.Append(proc.CreateParameter("acard", 200, 1, 48, localdb.topCard));
                        proc.Parameters.Append(proc.CreateParameter("an_cab", 3, 1, 2, (float)0));
                        proc.Parameters.Append(proc.CreateParameter("aclassif", 200, 1, 20, "organiz"));
                        proc.Parameters.Append(proc.CreateParameter("codes", 200, 1, 2000, organiz));
                        proc.Parameters.Append(proc.CreateParameter("aFlagsOriginal", 200, 1, 2000, ""));
                        proc.Parameters.Append(proc.CreateParameter("aOrigNums", 200, 1, 2000, ""));
                        proc.Parameters.Append(proc.CreateParameter("aCopyNums", 200, 1, 2000, ""));
                        proc.Parameters.Append(proc.CreateParameter("aDate", 200, 1, 2000, ""));
                        proc.Parameters.Append(proc.CreateParameter("aSend_Person", 200, 1, 2000, sendperson));
                        proc.Parameters.Append(proc.CreateParameter("aIsn_Delivery", 200, 1, 2000, ""));
                        proc.Parameters.Append(proc.CreateParameter("aSendingType", 3, 1, 4, (float)0));
                        proc.Parameters.Append(proc.CreateParameter("aIsnsContact", 200, 1, 2000, contact));
                        proc.Parameters.Append(proc.CreateParameter("aNotes", 200, 1, 8000, ""));
                        ApiConnection.ExecuteProc(proc);
                        if (ApiConnection.ErrCode != 0) throw new Exception("SaveSend [" +
                            ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("SaveSend || " + ex.Message);
            }

        }

        private static void SaveJournal(XmlNode journals, EApi.Head ApiConnection, Int32 isn_doc)
        {
            if (journals == null || ApiConnection == null || isn_doc == 0) return;
            XmlNodeList journal = journals.SelectNodes("ENTRY");
            for (int i = 0; i < journal.Count; i++)
            {
                try
                {
                    dynamic proc = ApiConnection.GetProc("add_journal");
                    proc.Parameters.Append(proc.CreateParameter("aisndoc", 3, 1, 4, (double)isn_doc));
                    proc.Parameters.Append(proc.CreateParameter("acard", 200, 1, 48, localdb.topCard));
                    proc.Parameters.Append(proc.CreateParameter("acab", 3, 1, 4, (float)0));
                    proc.Parameters.Append(proc.CreateParameter("acodes", 200, 1, 2000, localdb.syncDepartment(journal[i].SelectSingleNode("DUE_ADRESAT"))));
                    proc.Parameters.Append(proc.CreateParameter("aIsnNomenc", 3, 1, 4, DBNull.Value));
                    proc.Parameters.Append(proc.CreateParameter("aDates", 200, 1, 20, localdb.convertDate((journal[i].SelectNodes("SEND_DATE").Count > 0) ? journal[i].SelectSingleNode("SEND_DATE").InnerText : "")));
                    proc.Parameters.Append(proc.CreateParameter("aFlagsOriginal", 200, 1, 2000, (journal[i].SelectSingleNode("ORIG_FLAG").InnerText == "1") ? "1" : "0"));
                    proc.Parameters.Append(proc.CreateParameter("aOrigNums", 200, 1, 2000, (journal[i].SelectNodes("ORIGINAL_NUM").Count > 0) ? journal[i].SelectSingleNode("ORIGINAL_NUM").InnerText : ""));
                    proc.Parameters.Append(proc.CreateParameter("aCopyNums", 200, 1, 2000, (journal[i].SelectNodes("COPY_NAME").Count > 0) ? journal[i].SelectSingleNode("COPY_NAME").InnerText : ""));
                    proc.Parameters.Append(proc.CreateParameter("aClearFldr6", 3, 1, 4, (int)0));
                    proc.Parameters.Append(proc.CreateParameter("aDescructFlag", 3, 1, 2, (int)0));
                    ApiConnection.ExecuteProc(proc);
                    if (ApiConnection.ErrCode != 0) throw new Exception("SaveJournal [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());

                }
                catch (Exception ex)
                {
                    throw new Exception("SaveJournal || " + ex.Message);
                }
            }
        }
        private static void SaveCoverDoc(XmlNode CoverCoresps, EApi.Head ApiConnection, Int32 isn_doc)
        {
            if (CoverCoresps == null || ApiConnection == null || isn_doc == 0) return;
            XmlNodeList CoverCoresp = CoverCoresps.SelectNodes("CORRESP[CORRESP_KIND='2']");
            for (int i = 0; i < CoverCoresp.Count; i++)
            {
                string DUE_ORGANIZ = localdb.syncOrganiz(CoverCoresp[i].SelectSingleNode("DUE_ORGANIZ"));
                string ISN_ORGANIZ = localdb.syncOrganizISN(CoverCoresp[i].SelectSingleNode("DUE_ORGANIZ")).ToString();
                try
                {
                    dynamic proc = ApiConnection.GetProc("add_cover_doc");
                    proc.Parameters.Append(proc.CreateParameter("aisndoc", 3, 1, 4, (double)isn_doc));
                    proc.Parameters.Append(proc.CreateParameter("acard", 200, 1, 48, localdb.topCard));
                    proc.Parameters.Append(proc.CreateParameter("acab", 3, 1, 4, (float)0));
                    proc.Parameters.Append(proc.CreateParameter("acodes", 200, 1, 8000, DUE_ORGANIZ));
                    if (CoverCoresp[i].SelectNodes("CORRESP_NUM").Count > 0) proc.Parameters.Append(proc.CreateParameter("aCorrespNums", 200, 1, 8000,  CoverCoresp[i].SelectSingleNode("CORRESP_NUM").InnerText ));
                    else proc.Parameters.Append(proc.CreateParameter("aCorrespNums", 200, 1, 64,  DBNull.Value ));
                    if (CoverCoresp[i].SelectNodes("CORRESP_DATE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aCorrespDates", 200, 1, 8000,  localdb.convertDate(CoverCoresp[i].SelectSingleNode("CORRESP_DATE").InnerText)));
                    else proc.Parameters.Append(proc.CreateParameter("aCorrespDates", 200, 1, 20, DBNull.Value));
                    if (CoverCoresp[i].SelectNodes("CORRESP_SIGN").Count > 0) proc.Parameters.Append(proc.CreateParameter("aCorrespSigns", 200, 1, 8000, CoverCoresp[i].SelectSingleNode("CORRESP_SIGN").InnerText));
                    else proc.Parameters.Append(proc.CreateParameter("aCorrespSigns", 200, 1, 8000, DBNull.Value));
                    if (CoverCoresp[i].SelectNodes("ANNOTAT").Count > 0) proc.Parameters.Append(proc.CreateParameter("aAnnotats", 200, 1, 8000, CoverCoresp[i].SelectSingleNode("ANNOTAT").InnerText));
                    else proc.Parameters.Append(proc.CreateParameter("aAnnotats", 200, 1, 8000, DBNull.Value));
                    if (CoverCoresp[i].SelectNodes("CONSISTS").Count > 0) proc.Parameters.Append(proc.CreateParameter("aConsists", 200, 1, 8000, CoverCoresp[i].SelectSingleNode("CONSISTS").InnerText));
                    else proc.Parameters.Append(proc.CreateParameter("aConsists", 200, 1, 8000, DBNull.Value));
                    if (CoverCoresp[i].SelectNodes("NOTE").Count > 0) proc.Parameters.Append(proc.CreateParameter("aNotes", 200, 1, 8000, CoverCoresp[i].SelectSingleNode("NOTE").InnerText));
                    else proc.Parameters.Append(proc.CreateParameter("aNotes", 200, 1, 8000, DBNull.Value));

                    if (CoverCoresp[i].SelectNodes("ISN_CONTACT").Count > 0) proc.Parameters.Append(proc.CreateParameter("aIsnsContact", 200, 1, 8000, localdb.syncCoverContact(ISN_ORGANIZ, isn_doc)));
                    else proc.Parameters.Append(proc.CreateParameter("aIsnsContact", 200, 1, 8000, DBNull.Value));
                    ApiConnection.ExecuteProc(proc);
                    if (ApiConnection.ErrCode != 0) throw new Exception("SaveCoverDoc [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());

                }
                catch (Exception ex)
                {
                    throw new Exception("SaveCoverDoc || " + ex.Message);
                }
            }
        }        /// <summary>
        /// Добавление связок в документы
        /// </summary>
        /// <param name="links">Node содержащий связки</param>
        /// <param name="ApiConnection">Параметры Api - подключения</param>
        /// <param name="isn_doc">ISN текущго документа в базе в которую производится загрузка</param>
        /// <param name="aisndoc">ISN текущго документа в базе из которой производилась выгрузка</param>
        private static void SaveLinks(XmlNode links, EApi.Head ApiConnection, Int32 isn_doc, string aisndoc)
        {

            if (links == null || ApiConnection == null || isn_doc == 0) return;
            string aisn_linkdoc = "";
            string aisndoc_sync = isn_doc.ToString();
            string aisn_linkdoc_sync = "";
            string alinked_num = "";
            string aisn_link = "";
            string aisn_link_sync = "0";
            string aisn_link_para = "";
            string aisn_link_para_sync = "0";
            object result;

            XmlNodeList link = links.SelectNodes("LINK");
            for (int i = 0; i < link.Count; i++ )
            {
                alinked_num = (link[i].SelectNodes("LINKED_NUM").Count>0)?link[i].SelectSingleNode("LINKED_NUM").InnerText:"";
                aisn_link =(link[i].SelectNodes("LNK/CLASSIF_NAME").Count>0)?link[i].SelectSingleNode("LNK/CLASSIF_NAME").InnerText:"";
                
                string sql = "select ISN_LCLASSIF from " + localdb.sqlprefix + "LINK_CL where (CLASSIF_NAME ='" + aisn_link + "' )";

                OleDbCommand cmd = new OleDbCommand(sql, localdb.SyncConnection);
                result = cmd.ExecuteScalar();
                cmd.Dispose();
                if ((result != null) && (result != DBNull.Value))
                    aisn_link_sync = result.ToString();
                else
                {
                    aisn_link_sync = "0";
                    aisn_link_para_sync = "0";
                    if (link[i].SelectNodes("LNK/PLNK/CLASSIF_NAME").Count > 0)
                    {
                        aisn_link_para = link[i].SelectSingleNode("LNK/PLNK/CLASSIF_NAME").InnerText;
                    }
                    else aisn_link_para = "";

                    if ((aisn_link_para != aisn_link) && (aisn_link_para != ""))
                    {
                        sql = "select ISN_PARE_LINK from " + localdb.sqlprefix + "LINK_CL where (CLASSIF_NAME ='" + aisn_link_para + "' )";
                        cmd = new OleDbCommand(sql, localdb.SyncConnection);
                        result = cmd.ExecuteScalar();
                        cmd.Dispose();
                        if ((result != null) && (result != DBNull.Value))
                        {
                            aisn_link_sync = result.ToString();
                        }
                        else
                        {
                            localdb.InsertLink(aisn_link, aisn_link_para, out aisn_link_sync, out aisn_link_para_sync);
                        }
                    }
                    else localdb.InsertLink(aisn_link, aisn_link, out aisn_link_sync, out aisn_link_para_sync);
                }
                aisn_linkdoc = (link[i].SelectNodes("RC/ISN_DOC").Count > 0) ? link[i].SelectSingleNode("RC/ISN_DOC").InnerText : "";
                if (aisn_linkdoc != "")
                {
                    sql = "select importisn from protocol where (tname = 'RC') and (exportisn =" + aisn_linkdoc + " )";
                    cmd = new OleDbCommand(sql, localdb.Connection);
                    result = cmd.ExecuteScalar();
                    if ((result != null) && (result != DBNull.Value))
                        aisn_linkdoc_sync = result.ToString();
                    else aisn_linkdoc_sync = "";
                }
                if ((aisndoc != "") && (aisn_link != ""))
                {
                    if (aisn_linkdoc_sync != "")
                    {
                        sql = "select ISN_CLLINK from " + localdb.sqlprefix + "REF_LINK where (ISN_REF_DOC =" + aisndoc_sync + " )"
                            + " or (ISN_LINKED_DOC =" + aisndoc_sync + " )"
                            + " or (ISN_REF_DOC =" + aisn_linkdoc_sync + " )"
                            + " or (ISN_LINKED_DOC =" + aisn_linkdoc_sync + " )";
                        cmd = new OleDbCommand(sql, localdb.SyncConnection);
                        result = cmd.ExecuteScalar();
                        if ((result != null) && (result != DBNull.Value)) continue;
                        // выполняем добавление связки
                        dynamic proc = ApiConnection.GetProc("add_link");
                        proc.Parameters.Append(proc.CreateParameter("aisndoc", 3, 1, 4, double.Parse(aisndoc_sync)));
                        proc.Parameters.Append(proc.CreateParameter("aisn_linkdoc", 3, 1, 4, double.Parse(aisn_linkdoc_sync)));
                        proc.Parameters.Append(proc.CreateParameter("aisn_link", 3, 1, 4, double.Parse(aisn_link_sync)));
                        proc.Parameters.Append(proc.CreateParameter("alinked_num", 200, 1, 255, alinked_num));
                        proc.Parameters.Append(proc.CreateParameter("acard", 200, 1, 48, DBNull.Value));
                        proc.Parameters.Append(proc.CreateParameter("aUrlStr", 200, 1, 255, DBNull.Value));
                        ApiConnection.ExecuteProc(proc);
                        if (ApiConnection.ErrCode != 0) throw new Exception("SaveLINK [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
                    }
                    else
                    {
                        // выполняем добавление связки

                        dynamic proc = ApiConnection.GetProc("add_link");
                        proc.Parameters.Append(proc.CreateParameter("aisndoc", 3, 1, 4, double.Parse(aisndoc_sync)));
                        proc.Parameters.Append(proc.CreateParameter("aisn_linkdoc", 3, 1, 4, DBNull.Value));
                        proc.Parameters.Append(proc.CreateParameter("aisn_link", 3, 1, 4, double.Parse(aisn_link_sync)));
                        proc.Parameters.Append(proc.CreateParameter("alinked_num", 200, 1, 255, alinked_num));
                        proc.Parameters.Append(proc.CreateParameter("acard", 200, 1, 48, DBNull.Value));
                        proc.Parameters.Append(proc.CreateParameter("aUrlStr", 200, 1, 255, DBNull.Value));
                        ApiConnection.ExecuteProc(proc);
                        if (ApiConnection.ErrCode != 0) throw new Exception("SaveLINK [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
                    }
                }


            }
        }

        private static void SaveArRcValues(XmlNode ArRcValues, EApi.Head ApiConnection, Int32 isn_doc)
        {
            if (ArRcValues == null || ApiConnection == null || isn_doc == 0) return;
            XmlNodeList ArValue = ArRcValues.ChildNodes;
            for (int i = 0; i < ArValue.Count; i++)
            {
                try
                {
                    dynamic proc = ApiConnection.GetProc("edit_ar");
                    proc.Parameters.Append(proc.CreateParameter("aIsnOwner", 3, 1, 4, (double)isn_doc));
                    proc.Parameters.Append(proc.CreateParameter("aArName", 200, 1, 48, localdb.ARRCVALUE[ArValue[i].Name]));
                    //proc.Parameters.Append(proc.CreateParameter("aСard", 200, 1, 48, DBNull.Value)); // Русская буква "С"
                    proc.Parameters.Append(proc.CreateParameter("aCard", 200, 1, 48, DBNull.Value));
                    proc.Parameters.Append(proc.CreateParameter("aValue", 200, 1, 48, ArValue[i].InnerText));
                    ApiConnection.ExecuteProc(proc);
                    if (ApiConnection.ErrCode != 0) throw new Exception("SaveArRcValues [" + ApiConnection.ErrText + "]\n" + ApiConnection.ErrCode.ToString());
                }
                catch (Exception ex)
                {

                    throw new Exception("SaveArRcValues || " + ex.Message);
                }
            }
        }

    }
}
